
package App::SessionObject::ExtJS::Store;

$VERSION = do { my @r=(q$Revision: 19698 $=~/\d+/g); sprintf "%d."."%02d"x$#r,@r};

use App;
use App::SessionObject;
@ISA = ( "App::SessionObject" );

use strict;

sub load_rows {
    &App::sub_entry if ($App::trace);
    my ($self) = @_;
    my $context         = $self->{context};
    my $json_serializer = $context->serializer("json");
    my $count_column    = $self->{count_column} || "totalCount";
    my $rows_root       = $self->{rows_root}    || "data";
    my $total_count     = $context->so_get("total_count");
    my $table           = $context->so_get("table");
    my $params          = $context->so_get("params");
    my $sort            = $context->so_get("sort");
    my $dir             = $context->so_get("dir");
    my $callback        = $context->so_get("callback");

    if ($params) {
        $params = $json_serializer->deserialize($params);
    }
    else {
        $params = {};
    }

    my $columns = $context->so_get("columns");
    if ($columns) {
        $columns = [ split(/,/, $columns) ];
    }
    else {
        $columns = undef;
    }

    my $start   = $context->so_get("start") || 0;
    my $limit   = $context->so_get("limit");
    my $options = { startrow => $start+1, endrow => $start+$limit };
    if ($sort) {
        my $sort_spec = $sort;
        $sort_spec .= ".$dir" if ($dir);
        $options->{order_by} = [ $sort_spec ];
    }

    my $db      = $context->repository();
    my $rows    = $db->get_hashes($table, $params, $columns, $options);
    my $results = {
        $rows_root => $rows,
    };

    if ($total_count) {
        $results->{$count_column} = $total_count;
    }
    else {
        my $count   = $db->get($table, $params, "count(*)");
        $results->{$count_column} = $count;
    }

    my $json_text = $json_serializer->serialize($results);
    if ($callback) {
        $json_text = "$callback($json_text);";
    }

    &App::sub_exit($json_text) if ($App::trace);
    return($json_text);
}

1;

